﻿Imports System.Security.Cryptography
Public Class fUsuarios

    Public nuevo As Integer
    Public md5modificar As String


    Public Function MD5EncryptPass(ByVal StrPass As String) As String
        Dim PasConMd5 As String = ""
        Dim md5 As New MD5CryptoServiceProvider
        Dim bytValue() As Byte
        Dim bytHash() As Byte
        Dim i As Integer

        bytValue = System.Text.Encoding.UTF8.GetBytes(StrPass)

        bytHash = md5.ComputeHash(bytValue)
        md5.Clear()

        For i = 0 To bytHash.Length - 1
            PasConMd5 &= bytHash(i).ToString("x").PadLeft(2, "0")
        Next

        Return PasConMd5
    End Function
    Public Sub Mostrar()
        If guardar.Enabled = False Then
            guardar.Enabled = True
            cancelar.Enabled = True
            agregar.Enabled = False
            modificar.Enabled = False
            eliminar.Enabled = False
            imprimir.Enabled = False
            PanelArriba.Enabled = True
            PanelAbajo.Enabled = False
        Else
            cancelar.Enabled = False
            guardar.Enabled = False
            agregar.Enabled = True
            modificar.Enabled = True
            eliminar.Enabled = True
            imprimir.Enabled = True
            PanelArriba.Enabled = False
            PanelAbajo.Enabled = True

        End If
    End Sub

    Private Sub UsuariosBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UsuariosBindingNavigatorSaveItem.Click
        Me.Validate()
        Me.UsuariosBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.DbFireAndIceDataSet)

    End Sub

    Private Sub fUsuarios_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'DbFireAndIceDataSet._roles' table. You can move, or remove it, as needed.
        Me.RolesTableAdapter1.Fill(Me.DbFireAndIceDataSet._roles)
        'TODO: This line of code loads data into the 'DbFireAndIceDataSet.usuarios' table. You can move, or remove it, as needed.
        Me.UsuariosTableAdapter.Fill(Me.DbFireAndIceDataSet.usuarios)

    End Sub

    Private Sub agregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles agregar.Click
        nuevo = 1
        BindingNavigatorAddNewItem.PerformClick()
        SkinuserTextEdit.Text = "Money Twins"
        Mostrar()
    End Sub

    Private Sub modificar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles modificar.Click
        If IduserTextBox.Text = 1 Then
            MsgBox("No se puede modificar el Usuario: Admin")
        Else
            nuevo = 0
            md5modificar = ContrauserTextBox.Text
            Mostrar()
        End If
    End Sub

    Private Sub eliminar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles eliminar.Click
        If IduserTextBox.Text = 1 Then
            MsgBox("No se puede eliminar el Usuario: Admin")
        Else
            Dim opcion As Integer
            opcion = MsgBox("¿Está seguro que desea eliminar el registro?", MsgBoxStyle.YesNo + MsgBoxStyle.Question, "Eliminar registro")
            If opcion = vbYes Then
                Try

                
                    UsuariosTableAdapter.DeleteQuery(IduserTextBox.Text)
                    Me.UsuariosTableAdapter.Fill(Me.DbFireAndIceDataSet.usuarios)
                Catch ex As Exception
                    MsgBox("Lo sentimos, el registro no puede ser eliminado ya que está relacionado con otras tablas", MsgBoxStyle.Critical, "Error")
                End Try


            End If
        End If
    End Sub

    Private Sub guardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles guardar.Click
        Dim opcion As Integer

        Dim existe As Integer
        existe = Me.UsuariosTableAdapter.ScalarQueryUsuario(NombreuserTextBox.Text.Trim)
        If nuevo = 1 Then
            If existe <> 0 Then
                ErrorProvider1.SetError(NombreuserTextBox, "El nombre de Usuario ya existe, favor ingresar otro")
                Return
            End If
            ErrorProvider1.SetError(NombreuserTextBox, Nothing)
        End If



        If NombreuserTextBox.Text.Length = 0 Then
            ErrorProvider1.SetError(NombreuserTextBox, "Debe ingresar un nombre de Usuario")
            Return
        End If
        ErrorProvider1.SetError(NombreuserTextBox, Nothing)

        If ContrauserTextBox.Text.Length = 0 Then
            ErrorProvider1.SetError(ContrauserTextBox, "Debe ingresar una contraseña para el Usuario")
            Return
        End If
        ErrorProvider1.SetError(ContrauserTextBox, Nothing)


        If IdrolTextEdit.Text = "" Then
            ErrorProvider1.SetError(IdrolTextEdit, "Debe seleccionar un rol para este Usuario")
            Return
        End If
        ErrorProvider1.SetError(IdrolTextEdit, Nothing)




        Dim cadena As String = ""
        cadena = String.Format("¿Está seguro que desea guardar el Usuario: ({0}) con el ROL ({1})?", NombreuserTextBox.Text, IdrolTextEdit.Text)
        opcion = MsgBox(cadena, MsgBoxStyle.YesNo + MsgBoxStyle.Question, "Crear Usuario")
        If opcion = vbYes Then

   


            UsuariosBindingNavigatorSaveItem.PerformClick()

            If md5modificar <> ContrauserTextBox.Text.Trim Then
                Me.UsuariosTableAdapter.UpdateQueryContrasena(MD5EncryptPass(ContrauserTextBox.Text + "jova889"), IduserTextBox.Text)
                Me.UsuariosTableAdapter.Fill(Me.DbFireAndIceDataSet.usuarios)

            End If



            Mostrar()
        End If

    End Sub

    Private Sub cancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cancelar.Click
        ErrorProvider1.SetError(NombreuserTextBox, Nothing)
        Mostrar()
        Me.UsuariosTableAdapter.Fill(Me.DbFireAndIceDataSet.usuarios)
    End Sub

    Private Sub imprimir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles imprimir.Click
        GridControl1.ShowPrintPreview()
    End Sub
End Class